package com.yxj.cameraxapp;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.yxj.lib_camerax.CameraXView;

public class MainActivity extends AppCompatActivity {
    private CameraXView mCameraXView ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        mCameraXView = findViewById(R.id.mCameraXView);
        mCameraXView.openCamera(this, new CameraXView.OnStopListener() {
            @Override
            public void onStop(int code, String msg) {
                Log.v("[CameraXView]","[msg]->"+msg) ;
                if (code == 0){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Bitmap bit = BitmapFactory.decodeFile(msg);
                            Bitmap b = mCameraXView.isCameraFRONT()? mCameraXView.MirrorImage(bit):bit;
                            ((ImageView)findViewById(R.id.image)).setImageBitmap(b);
                        }
                    });
                }
            }
        });

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        findViewById(R.id.btnChange).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCameraXView.switchCamera();
            }
        });

        findViewById(R.id.btnTakePhoto).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCameraXView.takePicture();
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCameraXView!=null){
            mCameraXView.closeCamera();
        }
    }
}